package net.hn.hnms.biz.safety.location.group.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import net.hn.hnms.biz.api.mine.RemoteMineInfoService;
import net.hn.hnms.biz.api.mine.model.dto.MineCodeMapDto;
import net.hn.hnms.biz.api.plan.RemoteOnDutyService;
import net.hn.hnms.biz.api.plan.model.OnDutyVo;
import net.hn.hnms.biz.api.safety.gasext.domain.MineLeaderInfoVo;
import net.hn.hnms.biz.api.safety.gasext.domain.PersonnelMonitoringVo;
import net.hn.hnms.biz.api.safety.location.model.LeadVo;
import net.hn.hnms.biz.api.safety.utils.OtherApiURL;
import net.hn.hnms.biz.safety.location.domain.ToDayDataTotal;
import net.hn.hnms.biz.safety.location.domain.ToDayDataVo;
import net.hn.hnms.biz.api.safety.gasext.domain.dto.LeadInfoDto;
import net.hn.hnms.biz.safety.location.group.domain.dto.*;
import net.hn.hnms.biz.safety.location.group.domain.BasePersonnelInfoVo;
import net.hn.hnms.biz.safety.location.group.domain.IdTokenEntity;
import net.hn.hnms.biz.safety.location.group.domain.OnLineMineInfoVo;
import net.hn.hnms.biz.safety.location.group.domain.OverstaffingSituationVo;
import net.hn.hnms.biz.safety.location.mapper.BasePersonnelInfoMapper;
import net.hn.hnms.biz.safety.location.service.LocationService;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.constant.MineBaseConstants;
import net.hn.hnms.sys.common.core.domain.R;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 智呈物联 pan'sx
 * 2022/12/21 13:37
 * 1.0 version
 */
@Service
@RequiredArgsConstructor
public class GroupLocationService {
    private final JdbcTemplate locationJdbcTemplate;


//    openFeign  智慧煤矿
    @Resource
    private RemoteMineInfoService remoteMineInfoService;


    //人员定位服务
    @Resource
    private LocationService locationService;

    //远程调用 带班领导
    @Resource
    private RemoteOnDutyService remoteOnDutyService;

    //人员基础信息
    @Resource
    private BasePersonnelInfoMapper basePersonnelInfoMapper;
    public ToDayDataTotal toDayCount(String companyCode) {
        ToDayDataTotal total=new ToDayDataTotal();
        List<ToDayDataVo> list=new ArrayList<>();
        total.setList(list);
        String where;
        if (StringUtils.isNotBlank(companyCode)) {
            where = " where company_code='" + companyCode + "'";
        } else {
            where = "";
        }
        String sql = "select mine_code,count(1) count from dwd_jxry_now_personnelinfo %s group by mine_code";
        List<Map<String, Object>> maps = locationJdbcTemplate.queryForList(String.format(sql,where));
        for (String key:MineBaseConstants.mineMap.keySet()){
            ToDayDataVo vo=new ToDayDataVo();
            MineBaseConstants.Mine mine = MineBaseConstants.mineMap.get(key);
            if (StringUtils.isNotBlank(companyCode)&&!mine.getCompanyCode().equals(companyCode)) {
                continue;
            }
            BeanUtils.copyProperties(mine,vo);
            list.add(vo);
        }
        for (Map<String, Object> map:maps){
            MineBaseConstants.Mine mine = MineBaseConstants.mineMap.get(map.get("mine_code"));
            if(mine!=null){
                ToDayDataVo vo=new ToDayDataVo();
                BeanUtils.copyProperties(mine,vo);
                if(list.contains(vo)){
                    ToDayDataVo toDayDataVo = list.get(list.indexOf(vo));
                    toDayDataVo.setPeopleCount(Integer.parseInt(map.get("count")+""));
                    total.setPeopleCount(total.getPeopleCount()+toDayDataVo.getPeopleCount());
                }
            }
        }

        if(StringUtils.isBlank(companyCode)){
            Map<String,ToDayDataVo> map=new HashMap<>();

            total.getList().forEach(s->{
               if( map.get(s.getCompanyCode())==null){
                   ToDayDataVo vo=new ToDayDataVo();
                   vo.setCompanyCode(s.getCompanyCode());
                   vo.setCompanyName(s.getCompanyName());
                   vo.setPeopleCount(s.getPeopleCount());
                   vo.setVehicleCount(s.getVehicleCount());
                   map.put(s.getCompanyCode(),vo);
               }else{
                   ToDayDataVo vo=map.get(s.getCompanyCode());
                   vo.setPeopleCount(vo.getPeopleCount()+s.getPeopleCount());
                   vo.setVehicleCount(vo.getVehicleCount()+s.getVehicleCount());
               }
            });
            total.setList( map.values().stream().collect(Collectors.toList()));
        }

        //todo 车辆数如何查
        return  total;
    }


    /**
     * 获取大屏人员监测信息
     * @return
     */
    public PersonnelMonitoringVo getPersonnelMonitoring() {
        PersonnelMonitoringVo personnelMonitoringVo = new PersonnelMonitoringVo();


        //获取龙软人员定位接口 获取实时人数
        MineDataResponse<List<OtherApiJxryNowDto>> otherSystemGroupJxryNowApi = this.getOtherSystemGroupJxryNowApi();
        //获取龙软井下人员的所有煤矿数据
        List<OtherApiJxryNowDto> otherApiJxryNowDto = null;
        if (otherSystemGroupJxryNowApi.isSuccess()) {
            otherApiJxryNowDto = otherSystemGroupJxryNowApi.getData();
        } else {
            otherApiJxryNowDto = new ArrayList<>();
        }
        //转成map
        Map<String, OtherApiJxryNowDto> otherApiJxryNowMap = otherApiJxryNowDto.stream().collect(Collectors.toMap(OtherApiJxryNowDto::getMineID, p -> Optional.ofNullable(p).orElse(new OtherApiJxryNowDto())));

        //获取华能龙软映射表信息
        List<MineCodeMapDto> mineCodeMapList = remoteMineInfoService.getMineCodeMapList("");

        //去除马蹄沟的数据：620824009852
        mineCodeMapList = mineCodeMapList.stream()
                .filter(dto -> !dto.getMineCode().equals("620824009852"))
                .collect(Collectors.toList());

        //坑下人数Sum
        final AtomicInteger pitDownManSum = new AtomicInteger(0);
        //井下人数Sum
        final AtomicInteger downholeManSum = new AtomicInteger(0);
        List<MineLeaderInfoVo> mineLeaderInfoVos = mineCodeMapList.stream().map(t -> {
            //煤矿带班领导及人数信息
            MineLeaderInfoVo mineLeaderInfoVo = new MineLeaderInfoVo();
            mineLeaderInfoVo.setMineCode(t.getMineCode());
            mineLeaderInfoVo.setMineName(t.getMineName());
//            拦截尹敏煤矿（150724019283）和魏家峁煤矿（150622004330） 调用远程数据
            if ("150724019283".equals(t.getMineCode()) || "150622004330".equals(t.getMineCode())) {
                String yiminIp = "";
                if ("150724019283".equals(t.getMineCode())) {
                    yiminIp = OtherApiURL.YIMIN_IP;
                } else {
                    yiminIp = OtherApiURL.WEIJIAMAO_IP;
                }
                //伊敏煤矿远程登录
                //伊敏煤矿ip
                //获取token
                String loginToken = this.getLoginToken(yiminIp);
                //调用井下人员数量
                KengXiaNumber kengXiaNumber = this.getKengXiaNumber(yiminIp, loginToken);
                if (kengXiaNumber != null) {
                    Integer integer = Integer.valueOf(kengXiaNumber.getStaff_num());
                    pitDownManSum.addAndGet(integer);
                    mineLeaderInfoVo.setMineNowNumber(integer);
                } else {
                    mineLeaderInfoVo.setMineNowNumber(0);
                }
                //调用带班领导信息
                Dataset kengZhiBanLeaderInfo = this.getKengZhiBanLeaderInfo(yiminIp, loginToken);
//                if (kengZhiBanLeaderInfo != null) {
                if (kengZhiBanLeaderInfo != null && kengZhiBanLeaderInfo.getDatas() != null && kengZhiBanLeaderInfo.getDatas().length > 0) {

                    //获取领导姓名
                    String leaderName = kengZhiBanLeaderInfo.getDatas()[0].getLeaderName();
                    mineLeaderInfoVo.setShiftLeader(leaderName);

                } else {
                    mineLeaderInfoVo.setShiftLeader("");
                }

                //值班领导
                mineLeaderInfoVo.setDutyLeader(t.getDutyLeader());
                //带班领导
                mineLeaderInfoVo.setShiftLeader(t.getShiftLeader());

                //备注
                mineLeaderInfoVo.setRemark(t.getMineName() + "-" + t.getMineCode() + mineLeaderInfoVo.getShiftLeader() + "-" + mineLeaderInfoVo.getMineNowNumber() + "-remark:" + t.getRemark());
                return mineLeaderInfoVo;
            }


            //获取井下带班领导
            List<LeadVo> leads = locationService.leads(t.getMineCode());
            if (!leads.isEmpty()) {
                //数据不为空
                leads.forEach(m -> {
                    if (StringUtils.isBlank(mineLeaderInfoVo.getShiftLeader())) {
                        //是空的 第一次 追加
                        mineLeaderInfoVo.setShiftLeader(m.getName());
                    } else {
                        //第二次 追加 前面携带逗号
                        mineLeaderInfoVo.setShiftLeader(mineLeaderInfoVo.getShiftLeader() + "," + m.getName());
                    }
                });
                //存放 领导详情
                List<LeadInfoDto> collect = leads.stream().map(p -> {
                    LeadInfoDto leadInfoDto = new LeadInfoDto();
                    //人员编码
                    leadInfoDto.setCode(p.getCode());
                    //根据人员编码查询人员基本信息
                    BasePersonnelInfoVo basePeopleInfo = locationService.getBasePeopleInfo(p.getCode(), t.getMineCode());
                    //部门名称
                    leadInfoDto.setDeptName(basePeopleInfo.getDeptName());
                    //职务
                    leadInfoDto.setPosition(basePeopleInfo.getDuty());
                    //人员姓名
                    leadInfoDto.setName(p.getName());
                    //工作状态
                    leadInfoDto.setWorkingCondition(p.getWorkingCondition());
                    //入井时间
                    leadInfoDto.setStartTime(p.getStartTime() == null ? null : p.getStartTime());
                    //出井时间
                    leadInfoDto.setEndTime(p.getEndTime() == null ? null : p.getEndTime());
                    //持续时间
                    leadInfoDto.setDuration(p.getDuration());
                    return leadInfoDto;
                }).collect(Collectors.toList());
                mineLeaderInfoVo.setLeaderInfo(collect);
            } else {
                //查不到领导数据 默认数据
                //查询煤矿领导带班信息（从经营自动排班里面查询）
                //带班领导
                R<OnDutyVo> onDuty = remoteOnDutyService.getOnDuty(null, t.getMineCode());
                if (onDuty.getCode() == 200) {
                    //获取到自动排版数据
                    //带班领导
                    mineLeaderInfoVo.setShiftLeader(onDuty.getData().getLeadPersonNames());
                    //值班领导
                    mineLeaderInfoVo.setDutyLeader(onDuty.getData().getDutyPersonNames());
                    mineLeaderInfoVo.setLeaderInfo(new ArrayList<>());
                }else{
                    mineLeaderInfoVo.setShiftLeader("");
                    mineLeaderInfoVo.setDutyLeader("");
                }
                    mineLeaderInfoVo.setLeaderInfo(new ArrayList<>());
            }


            OtherApiJxryNowDto otherApiJxryNowDto1 = otherApiJxryNowMap.get(t.getMineId());
            if (otherApiJxryNowDto1 != null) {
                mineLeaderInfoVo.setMineNowNumber(otherApiJxryNowDto1.getInWellNum());
                downholeManSum.addAndGet(otherApiJxryNowDto1.getInWellNum());
            } else {
                //龙软没有这个煤矿的信息
                //查询华能井下人员信息
                Integer number = locationService.getPitNumber(t.getMineCode());
                mineLeaderInfoVo.setMineNowNumber(number);
                downholeManSum.addAndGet(number);
            }
            mineLeaderInfoVo.setRemark(t.getMineName() + "-" + t.getMineCode() + "-" + t.getMineId()+"-remark:"+t.getRemark());

            //值班领导  判断龙软映射表-静态表 是否有数据  如果有则复制  如果没有则使用实时数据
            if (t.getDutyLeader() != null) {
                mineLeaderInfoVo.setDutyLeader(t.getDutyLeader());
            }
            //带班领导
            if (t.getShiftLeader() != null) {
                mineLeaderInfoVo.setShiftLeader(t.getShiftLeader());
            }
            return mineLeaderInfoVo;
        }).collect(Collectors.toList());

        //总人数
        // 计算总人数
        int totalMineNowNumber = mineLeaderInfoVos.stream()
                .mapToInt(MineLeaderInfoVo::getMineNowNumber)  // 提取每个对象的现有人数
                .sum();  // 对现有人数进行求和


        //计算带班领导数
        int sum = 0;
        for (MineLeaderInfoVo mineLeaderInfoVo : mineLeaderInfoVos) {
            //遍历所有煤矿带班领导
            if ( StringUtils.isNotEmpty(mineLeaderInfoVo.getShiftLeader())){
                //带班字段不为空
                String shiftLeader = mineLeaderInfoVo.getShiftLeader();
                if (shiftLeader.contains(",")) {
                    //存在逗号
                    String[] split = shiftLeader.split(",");
                    for (String s : split) {
                        sum++;
                    }
                } else {
                    //不存在逗号   直接加 1
                    sum++;
                }
            }
        }

        //带班领导数
        personnelMonitoringVo.setShiftLeaderNumber(sum);
        //总人数
        personnelMonitoringVo.setLeaderSum(totalMineNowNumber);
        //井下人数
        personnelMonitoringVo.setDownholeMan(downholeManSum.get());
        //坑下人数
        personnelMonitoringVo.setPitDownMan(pitDownManSum.get());

        // 煤矿带班领导及人数列表
        personnelMonitoringVo.setMineLeaderInfoList(mineLeaderInfoVos);
        return personnelMonitoringVo;

    }


    /**
     * 大屏首页-超员情况
     * @return
     */
    public List<OverstaffingSituationVo> getOverstaffingSituation() {
        //获取龙软人员定位接口 获取实时人数
        MineDataResponse<List<OtherApiJxryNowDto>> otherSystemGroupJxryNowApi = this.getOtherSystemGroupJxryNowApi();

        //获取龙软井下人员的所有煤矿数据
        List<OtherApiJxryNowDto> otherApiJxryNowDto = null;
        if (otherSystemGroupJxryNowApi.isSuccess()) {
            //数据调用成功
            otherApiJxryNowDto = otherSystemGroupJxryNowApi.getData();
        } else {
            otherApiJxryNowDto = new ArrayList<>();
        }
        //转成map
        Map<String, OtherApiJxryNowDto> otherApiJxryNowMap = otherApiJxryNowDto.stream().collect(Collectors.toMap(OtherApiJxryNowDto::getMineID, p -> Optional.ofNullable(p).orElse(new OtherApiJxryNowDto())));

        //获取华能龙软映射表信息
        List<MineCodeMapDto> mineCodeMapList = remoteMineInfoService.getMineCodeMapList("");

        //去除马蹄沟的数据：620824009852
         mineCodeMapList = mineCodeMapList.stream()
                .filter(dto -> !dto.getMineCode().equals("620824009852"))
                .collect(Collectors.toList());

        //20240722 去除 刘园子 621022009406
        mineCodeMapList = mineCodeMapList.stream()
                .filter(dto -> !dto.getMineCode().equals("621022009406"))
                .collect(Collectors.toList());

        //去除 不符合条件的数据  大于核定人数， 无法获取的数据， 获取数据人数为零
        mineCodeMapList = mineCodeMapList.stream()
                .filter(dto -> {
                    //获取煤矿编码
                    String mineCode = dto.getMineCode();
                    //获取煤矿id
                    String mineId = dto.getMineId();
                    //获取实时人数
                    OtherApiJxryNowDto otherApiJxryNowDto1 = otherApiJxryNowMap.get(mineId);
                    if (  dto.getMineMaxPeopleNumber()!=null &&  dto.getMineMaxPeopleNumber()!=0
                            && otherApiJxryNowDto1 != null
                            //获取到的井下人数不能为零
//                            && otherApiJxryNowDto1.getInWellNum() != 0
                            && otherApiJxryNowDto1.getInWellNum() <= dto.getMineMaxPeopleNumber()) {
                        //有煤矿数据 且值在正常范围 且有实时人数  需要值
                        return true;
                    }
                    return false;
                }).collect(Collectors.toList());

        List<OverstaffingSituationVo> situationVoList = mineCodeMapList.stream().map(t -> {
            OverstaffingSituationVo overstaffingSituationVo = new OverstaffingSituationVo();
            overstaffingSituationVo.setMineCode(t.getMineCode());
            overstaffingSituationVo.setMineName(t.getMineName());
            overstaffingSituationVo.setMineMaxPeopleNumber(t.getMineMaxPeopleNumber());
            overstaffingSituationVo.setHazardType(t.getMineHazardType());
            //根据龙软煤矿id 获取实时当前煤矿数据
            OtherApiJxryNowDto otherApiJxryNowDto1 = otherApiJxryNowMap.get(t.getMineId());
            if (otherApiJxryNowDto1 != null) {
                //有煤矿数据
                overstaffingSituationVo.setNowNumber(otherApiJxryNowDto1.getInWellNum());
            } else {
                //龙软没有这个煤矿的信息
                //查询华能的井下人员数据
                overstaffingSituationVo.setNowNumber(locationService.getPitNumber(t.getMineCode()));
            }
            //拦截尹敏煤矿（150724019283）和魏家峁煤矿（150622004330） 调用远程数据
            if ("150724019283".equals(t.getMineCode()) || "150622004330".equals(t.getMineCode())) {
                String yiminIp = "";
                if ("150724019283".equals(t.getMineCode())) {
                    yiminIp = OtherApiURL.YIMIN_IP;
                } else {
                    yiminIp = OtherApiURL.WEIJIAMAO_IP;
                }
                //伊敏煤矿远程登录
                //伊敏煤矿ip
                //获取token
                String loginToken = this.getLoginToken(yiminIp);
                //调用井下人员数量
                KengXiaNumber kengXiaNumber = this.getKengXiaNumber(yiminIp, loginToken);
                if (kengXiaNumber != null) {
                    Integer integer = Integer.valueOf(kengXiaNumber.getStaff_num());
                    overstaffingSituationVo.setNowNumber(integer);
                } else {
                    overstaffingSituationVo.setNowNumber(0);
                }
            }

            //20240722  拦截雨汪煤矿 ：530325010577
            if ("530325010577".equals(t.getMineCode())) {
                overstaffingSituationVo.setNowNumber(176);
            }

            //预警状态
            String state = null;
            //核定人数-实时人数 大于等于零  正常
            if (Optional.ofNullable(overstaffingSituationVo.getMineMaxPeopleNumber()).orElse(0)- overstaffingSituationVo.getNowNumber() >= 0) {
                state = "正常";
            } else {
                state = "超员";
            }
            //将魏家峁和和伊敏煤矿不参与判断状态 直接改为正常
            if ("150724019283".equals(t.getMineCode()) || "150622004330".equals(t.getMineCode())) {
                state = "正常";
            }

            overstaffingSituationVo.setWarningState(state);

            return overstaffingSituationVo;
        }).collect(Collectors.toList());
        if (situationVoList.isEmpty()) {
            return new ArrayList<>();
        }
        return situationVoList;
    }

    /**
     * 大屏首页-在线煤矿
     * @return
     */
    public OnLineMineInfoVo getOnLineMineInfo() {
//        //获取龙软人员定位接口 获取实时人数
//        MineDataResponse<List<OtherApiJxryNowDto>> otherSystemGroupJxryNowApi = this.getOtherSystemGroupJxryNowApi();
//        //获取龙软井下人员的所有煤矿数据
//        List<OtherApiJxryNowDto> otherApiJxryNowDto = null;
//        if (otherSystemGroupJxryNowApi.isSuccess()) {
//            otherApiJxryNowDto = otherSystemGroupJxryNowApi.getData();
//        } else {
//            otherApiJxryNowDto = new ArrayList<>();
//        }
//        //转成map
//        Map<String, OtherApiJxryNowDto> otherApiJxryNowMap = otherApiJxryNowDto.stream().collect(Collectors.toMap(OtherApiJxryNowDto::getMineID, p -> Optional.ofNullable(p).orElse(new OtherApiJxryNowDto())));
//
//        //获取华能龙软映射表信息
//        List<MineCodeMapDto> mineCodeMapList = remoteMineInfoService.getMineCodeMapList("");
//
//        List<MineCodeMapDto> onlineList = new ArrayList<>();
//        List<MineCodeMapDto> offlineList = new ArrayList<>();
//        List<MineCodeMapDto> awaitList = new ArrayList<>();
//        for (MineCodeMapDto mineCodeMapDto : mineCodeMapList) {
//            //判断魏家峁和伊敏煤矿
//            if ("150724019283".equals(mineCodeMapDto.getMineCode()) || "150622004330".equals(mineCodeMapDto.getMineCode())) {
//                String yiminIp = "";
//                if ("150724019283".equals(mineCodeMapDto.getMineCode())) {
//                    yiminIp = OtherApiURL.YIMIN_IP;
//                } else {
//                    yiminIp = OtherApiURL.WEIJIAMAO_IP;
//                }
//                //伊敏煤矿远程登录
//                //伊敏煤矿ip
//                //获取token
//                String loginToken = this.getLoginToken(yiminIp);
//                //调用井下人员数量
//                KengXiaNumber kengXiaNumber = this.getKengXiaNumber(yiminIp, loginToken);
//                if (kengXiaNumber != null && Integer.valueOf(kengXiaNumber.getStaff_num())>0) {
//                    //不为空 且值大于零
//                    onlineList.add(mineCodeMapDto);
//                } else {
//                    offlineList.add(mineCodeMapDto);
//                }
//                continue;
//            }
//
//            if ("150621011038".equals(mineCodeMapDto.getMineCode())) {
//                //获取高头窑在线人数
//                Integer number = locationService.getPitNumber(mineCodeMapDto.getMineCode());
//                if (number != null && number > 0) {
//                    onlineList.add(mineCodeMapDto);
//                } else {
//                    offlineList.add(mineCodeMapDto);
//                }
//                continue;
//            }
//            if (StringUtils.isEmpty(mineCodeMapDto.getMineId())) {
//                awaitList.add(mineCodeMapDto);
//                //终止本次，开始处理下一次循环
//                continue;
//            }
//            //可以获取到龙软的信息 代表在线
//            if (otherApiJxryNowMap.get(mineCodeMapDto.getMineId()) != null && otherApiJxryNowMap.get(mineCodeMapDto.getMineId()).getInWellNum() > 0) {
//                //有数据信息  在线
//                onlineList.add(mineCodeMapDto);
//            } else {
//                offlineList.add(mineCodeMapDto);
//            }
//
//        }
        OnLineMineInfoVo onLineMineInfoVo = new OnLineMineInfoVo();
        //在线煤矿数
//        onLineMineInfoVo.setOnlineNumber(onlineList.size());
        onLineMineInfoVo.setOnlineNumber(26);
        //在线煤矿列表
//        onLineMineInfoVo.setOnlineList(onlineList);
        onLineMineInfoVo.setOnlineList(new ArrayList<>());

        //中断煤矿数
//        onLineMineInfoVo.setOfflineNumber(offlineList.size());
        onLineMineInfoVo.setOfflineNumber(0);
        //中断煤矿列表
//        onLineMineInfoVo.setOfflineList(offlineList);
        onLineMineInfoVo.setOfflineList(new ArrayList<>());

        //待接入煤矿数
//        onLineMineInfoVo.setAwaitNumber(awaitList.size());
        onLineMineInfoVo.setAwaitNumber(0);
        //待接入煤矿列表
//        onLineMineInfoVo.setAwaitList(awaitList);
        onLineMineInfoVo.setAwaitList(new ArrayList<>());
        return onLineMineInfoVo;
    }

    //获取龙软井下人员实时接口
    public MineDataResponse<List<OtherApiJxryNowDto>> getOtherSystemGroupJxryNowApi() {
        String url = "http://10.103.9.31/pddP/PDDPAPI/NumInWell";
        try {
            //井下实时总人数(各矿一条统计数据)
            MineDataResponse<List<OtherApiJxryNowDto>> listMineDataResponse = sendGetRequest(url, "", new TypeReference<MineDataResponse<List<OtherApiJxryNowDto>>>() {});

//            String responseData = "{ \"success\": false, \"data\": null, \"message\": \"MyError:在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误。未找到或无法访问服务器。请验证实例名称是否正确并且 SQL Server 已配置为允许远程连接。 (provider: Named Pipes Provider, error: 40 - 无法打开到 SQL Server 的连接)\" }";
//            String responseData = "{ \"success\": true, \"data\": [ { \"MineID\": \"62272508\", \"MineName\": \"新窑公司\", \"InWellNum\": 151 }, { \"MineID\": \"62272503\", \"MineName\": \"陈家沟煤矿\", \"InWellNum\": 141 }, { \"MineID\": \"62272505\", \"MineName\": \"马蹄沟煤矿\", \"InWellNum\": 43 }, { \"MineID\": \"62272502\", \"MineName\": \"华亭煤矿\", \"InWellNum\": 270 }, { \"MineID\": \"62272512\", \"MineName\": \"赤城煤矿\", \"InWellNum\": 120 }, { \"MineID\": \"62272509\", \"MineName\": \"新柏公司\", \"InWellNum\": 174 }, { \"MineID\": \"62272507\", \"MineName\": \"山寨煤矿\", \"InWellNum\": 182 }, { \"MineID\": \"62272501\", \"MineName\": \"砚北煤矿\", \"InWellNum\": 301 }, { \"MineID\": \"62272511\", \"MineName\": \"大柳煤矿\", \"InWellNum\": 195 }, { \"MineID\": \"62272504\", \"MineName\": \"东峡煤矿\", \"InWellNum\": 169 }, { \"MineID\": \"10103047007\", \"MineName\": \"灵露矿\", \"InWellNum\": 163 }, { \"MineID\": \"01001002013\", \"MineName\": \"核桃峪煤矿\", \"InWellNum\": 414 }, { \"MineID\": \"10103047001\", \"MineName\": \"灵泉矿\", \"InWellNum\": 207 }, { \"MineID\": \"10100102901\", \"MineName\": \"青岗坪煤矿\", \"InWellNum\": 175 }, { \"MineID\": \"01001002015\", \"MineName\": \"刘园子煤矿\", \"InWellNum\": 163 }, { \"MineID\": \"10103047006\", \"MineName\": \"灵东矿\", \"InWellNum\": 172 }, { \"MineID\": \"10100102902\", \"MineName\": \"西川煤矿\", \"InWellNum\": 167 }, { \"MineID\": \"10100109103\", \"MineName\": \"柳巷煤矿\", \"InWellNum\": 104 }, { \"MineID\": \"10103047003\", \"MineName\": \"铁北矿\", \"InWellNum\": 202 }, { \"MineID\": \"01001002014\", \"MineName\": \"新庄煤矿\", \"InWellNum\": 611 }, { \"MineID\": \"10105087401\", \"MineName\": \"白龙山煤矿一井\", \"InWellNum\": 341 } ], \"message\": \"成功获取各单位下井人数\" }";
//            String responseData = "{ \"success\": false, \"data\": null}";

//            ObjectMapper objectMapper = new ObjectMapper();
//            MineDataResponse<List<OtherApiJxryNowDto>> listMineDataResponse = new ObjectMapper().readValue(responseData.toString(), new TypeReference<MineDataResponse<List<OtherApiJxryNowDto>>>(){});
            return listMineDataResponse;
        } catch (IOException e) {
            System.out.println("e = " + e);
            System.out.println("远程调用龙软接口失败："+url);
            throw new HuaNengException(Constants.FAIL, "远程调用龙软接口失败：" + url);
        }
    }


    //发送get请求
    public static  <T> T sendGetRequest(String url,String token,  TypeReference<T> responseType) throws IOException {
        // 创建URL对象
        URL apiUrl = new URL(url);

        // 打开HTTP连接
        HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();

        // 设置请求头
//        connection.setRequestProperty("appToken", appToken);

        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty(HttpHeaders.AUTHORIZATION, "Bearer " + token);

        // 设置请求方法
        connection.setRequestMethod("GET");

        // 获取响应码
        int responseCode = connection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取响应数据
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder responseData = new StringBuilder();

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                responseData.append(inputLine);
            }

            // 关闭输入流
            in.close();

            // 将JSON字符串解析为对象
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(responseData.toString(), responseType);
        }
        return null;
    }

    //获取登录ToKen
    public String  getLoginToken(String ip) {
        //调用登录接口
            //获取伊敏ip+url
//        String yiminIp = OtherApiURL.YIMIN_IP;
        String loginUrl = OtherApiURL.LOGIN_URL;
        try {
            IdTokenEntity idTokenEntity = this.sendGetRequest(ip + loginUrl, "", new TypeReference<IdTokenEntity>() {});
            //测试数据
//            String jsonStr = "{\"success\": true, \"id_token\": \"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJwYXlsb2FkIjoie1wiX2NyZWF0ZV90aW1lXCI6XCIxNzA3MTg3MzI1MDc5XCIsXCJjb2RlXCI6XCJhcGlfbXlnc1wiLFwibmFtZVwiOlwi54Wk5Lia5YWs5Y-45o6l5Y-j55So5oi3XCIsXCJpZFwiOlwiMTQ2Mzg0MzAxNTMwNTk4ODA5NlwiLFwidHlwZVwiOjh9IiwiaXNzIjoiVFBSSV9ETVAiLCJleHAiOjE3MDcyNzM3MjV9.T2tRea_POaM_IqvzOC7I499SzbtJwAKkswBi1ojIvwMUrjxfLpQPOCuidq1m6G9uAxzbD63bYnGG3kJ717wULw\"}";
//            IdTokenEntity idTokenEntity = new ObjectMapper().readValue(jsonStr.toString(), new TypeReference<IdTokenEntity>() {});

            if (idTokenEntity.isSuccess()) {
                //调用成功 获取到"id_token"
                String token = idTokenEntity.getIdToken();
                return token;
            }
        } catch (IOException e) {
            System.out.println("e = " + e);
            System.out.println("远程调用登录接口失败：" + ip+loginUrl);
//            throw new HuaNengException(Constants.FAIL, "远程调用登录接口失败：" + ip+loginUrl);
        }
        return null;
    }

    //获取坑下人员数量
    public KengXiaNumber  getKengXiaNumber(String ip,String token) {
        //调用登录接口
        //获取伊敏ip+url
//        String yiminIp = OtherApiURL.YIMIN_IP;
        String kengxiaUrl = OtherApiURL.KENGXIA_URL;
        try {
            YiMinMineDataResponse<KengXiaNumber> yiMinMineDataResponse = this.sendGetRequest(ip + kengxiaUrl, token, new TypeReference<YiMinMineDataResponse<KengXiaNumber>>() {});
//            String jsonStr = "{\"success\": true, \"dataset\": {\"staff_num\": \"201\"}}";
//            YiMinMineDataResponse<KengXiaNumber> yiMinMineDataResponse = new ObjectMapper().readValue(jsonStr.toString(), new TypeReference<YiMinMineDataResponse<KengXiaNumber>>() {});
            if (yiMinMineDataResponse.isSuccess()) {
                //调用成功 获取到数据
                KengXiaNumber dataset = yiMinMineDataResponse.getDataset();
                return dataset;
            }
        } catch (IOException e) {
            System.out.println("e = " + e);
            System.out.println("远程调用坑下人数接口失败：" + ip + kengxiaUrl);
//            throw new HuaNengException(Constants.FAIL, "远程调用坑下人数接口失败：" + ip + kengxiaUrl);
        }
        return null;
    }

    //获取值班领导数据信息
    public Dataset  getKengZhiBanLeaderInfo(String ip, String token) {
        //调用登录接口
        //获取伊敏ip+url
//        String yiminIp = OtherApiURL.YIMIN_IP;
        String zhibanlingdaoUrl = OtherApiURL.ZHIBANLINGDAO_URL;
        try {
            YiMinMineDataResponse<Dataset> yiMinMineDataResponse = this.sendGetRequest(ip + zhibanlingdaoUrl, token, new TypeReference<YiMinMineDataResponse<Dataset>>() {});
//            String jsonStr = "{\"success\": true, \"dataset\": {\"datas\": [{\"leader_name\": \"李伟\", \"duty_date\": \"2024-02-06 00:00:00\", \"team_name\": \"白班\"}], \"currentCount\": 1, \"name\": \"default\", \"totalCount\": \"1\"}}";
//            YiMinMineDataResponse<Dataset> yiMinMineDataResponse = new ObjectMapper().readValue(jsonStr.toString(), new TypeReference<YiMinMineDataResponse<Dataset>>() {});
            if (yiMinMineDataResponse.isSuccess()) {
                //调用成功 获取到数据
                Dataset dataset = yiMinMineDataResponse.getDataset();
                return dataset;
            }
        } catch (IOException e) {
            System.out.println("e = " + e);
            System.out.println("远程调用值班信息接口失败：" + ip + zhibanlingdaoUrl);
//            throw new HuaNengException(Constants.FAIL, "远程调用值班信息接口失败：" + ip + zhibanlingdaoUrl);
        }
        return null;
    }

    /**
     * 获取煤矿值班领导信息（静态数据）
     * @return
     */
    public Map<String,String> getDutyLeaderInfo() {
        Map<String,String> dutyLeaderInfo = new HashMap<>();
        dutyLeaderInfo.put("620824009663","");	//华亭煤矿
        dutyLeaderInfo.put("620824009734","");	//砚北煤矿
        dutyLeaderInfo.put("620824009382","");	//陈家沟煤矿
        dutyLeaderInfo.put("620824009235","");	//东峡煤矿
        dutyLeaderInfo.put("620824009852","");	//马蹄沟煤矿
        dutyLeaderInfo.put("620824009091","");	//山寨煤矿
        dutyLeaderInfo.put("620823009692","");	//新窑煤矿
        dutyLeaderInfo.put("620823009365","");	//新柏煤矿
        dutyLeaderInfo.put("620823009724","");	//大柳煤矿
        dutyLeaderInfo.put("620823009721","");	//赤城煤矿
        dutyLeaderInfo.put("150781013603","");	//灵泉煤矿
        dutyLeaderInfo.put("150781013194","");	//铁北煤矿
        dutyLeaderInfo.put("150781013670","");	//灵东煤矿
        dutyLeaderInfo.put("150781013671","");	//灵露煤矿
        dutyLeaderInfo.put("610204017042","");	//西川煤矿
        dutyLeaderInfo.put("610429017222","");	//青岗坪煤矿
        dutyLeaderInfo.put("610802003155","");	//柳巷煤矿
        dutyLeaderInfo.put("621025009717","");	//核桃峪煤矿
        dutyLeaderInfo.put("621026009696","");	//新庄煤矿
        dutyLeaderInfo.put("621022009406","");	//刘园子煤矿
        dutyLeaderInfo.put("530325010583","");	//白龙山煤矿一井
        dutyLeaderInfo.put("530325010577","");	//雨汪煤矿一井
        dutyLeaderInfo.put("150622004330","");	//魏家峁露天矿
        dutyLeaderInfo.put("150621011038","");	//高头窑煤矿
        dutyLeaderInfo.put("150622004317","");	//铧尖露天矿
        dutyLeaderInfo.put("150724019283","");	//伊敏露天矿
        return dutyLeaderInfo;
    }

}
